package com.aliyun.messagemgt.application.service.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhangbixing
 * @Date: 2019/1/31 16:05
 * @description:
 */
@Service
public class MessageQueenServiceImpl implements MessageQueenService, InitializingBean {

    //@Value("${MQ.rocket.producerId}")
    private String groupId;
    //@Value("${MQ.rocket.accessKey}")
    private String accessKey;
    //@Value("${MQ.rocket.secretKey}")
    private String secretKey;
    //@Value("${MQ.rocket.ONSAddr}")
    private String onsAddr;
    //@Value("${MQ.rocket.topic}")
    private String topic;

    private Producer producer = null;

    /**
     * MQ 限制条数
     */
    private final static int MQ_SIZE_LIMIT = 100;

    /**
     * 发送map类型的消息
     *
     * @return
     */
    @Override
    public SendResult sendMessage(Map<String, Object> obj, String tag) {
        JSONObject json = new JSONObject(obj);
        byte[] bytes = JSONObject.toJSONBytes(json);
        Message message = new Message(topic, tag, bytes);
        SendResult sendResult = producer.send(message);
        return sendResult;
    }

    @Override
    public void sendMessage(Object obj, String tag) {
        Message msg = new Message(topic, tag, JSONObject.toJSONBytes(obj));
        producer.send(msg);
    }

    @Override
    public void sendMessageList(List objs, String tag) {
        List<Object> subMsgs = new ArrayList<>();
        for (Object message : objs) {
            subMsgs.add(message);
            if (subMsgs.size() >= MQ_SIZE_LIMIT) {
                Message msg = new Message(topic, tag, JSONObject.toJSONBytes(subMsgs));
                producer.send(msg);
                subMsgs = new ArrayList();
            }
        }
        if (subMsgs.size() > 0) {
            Message lastMsg = new Message(topic, tag, JSONObject.toJSONBytes(subMsgs));
            producer.send(lastMsg);
        }
    }

    @Override
    public void afterPropertiesSet() {
    }
}
